package com.sname.demoribbon.controller;

import com.sname.demoribbon.command.HelloServiceObserveCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Observer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author 宋贤坤
 * @date 2018/11/19 17:11
 */
@RestController
@RequestMapping
public class ConsumerControllerTwo {
    @Autowired
    @Qualifier("helloServiceObserveCommand")
    private HelloServiceObserveCommand helloService;
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/consumer")
    public String helloConsumer() throws ExecutionException, InterruptedException {
        List<String> list = new ArrayList<String>();

//        return helloService.helloService();

//        HelloServiceCommand command = new HelloServiceCommand("hello", restTemplate);

//        String result = command.execute();
        //execute() 方法调用,获取到结果;execute() 应该是同步执行,.queue()应该是异步执行;

        /**改造：*/
//        Future<String> future = command.queue();
//        return future.get();
        /**再次改造*/
//        Long now = System.currentTimeMillis();
//        Future<String> future = command.queue();
//        System.out.println(11111);
//        Long end = System.currentTimeMillis();
//        System.out.println(end - now);
//        String result = future.get();
//        Long lase = System.currentTimeMillis() - end;
//        System.out.println(lase);
//        return result;

        /**再再改造*/
        HelloServiceObserveCommand command = new HelloServiceObserveCommand("hello", restTemplate);
        //执行的方法
        Observable observable = command.observe();
        //上面这种方法是热执行Observable observable = command.observe();
        // command.toObservable();  这个方法是冷执行 ;冷执行是等所有的执行都执行完了所有的注册都到位了后再来执行这个方法;热执行就恰好相反


        observable.subscribe(new Observer<String>() {
            @Override
            public void onCompleted() {
                System.out.println("聚合完了所有的查询请求");
            }

            @Override
            public void onError(Throwable throwable) {
                //如果发生错误就打印错误!
                throwable.printStackTrace();

            }

            @Override
            public void onNext(String o) {
                //聚合结果
                //在后面的逻辑代码中有好几个onNext()方法,每次都会返回结果到这个位置来;
                //所以此处就将这些结果聚合起来装在一个集合里面
                System.out.println("结果来啦 -----------");
                list.add(o);
            }
        });
        return list.toString();
    }
}